package observer;

import java.util.List;

/**
 * @ClassName ObserverPatternDemo
 * @Description 观察者模式
 * @Author leejiliang
 * @DateTime 2021/2/24 16:02
 * @Version 1.0
 */
public class ObserverPatternDemo {

	public static void main(String[] args) {
		final ConcreteObserve concreteObserve = new ConcreteObserve();
		concreteObserve.change();
	}

	public interface Observer{
		void update();
	}

	public abstract static class ObserverManager{
		private List<Observer> observers = List.of(new ObserverA(), new ObserverB());

		public void addObserver(Observer observer) {
			observers.add(observer);
		}

		public void remove(Observer observer) {
			observers.remove(observer);
		}

		protected void notifyAllObserver() {
			observers.forEach(Observer::update);
		}

		public abstract void change();
	}

	static class ObserverA implements Observer{

		@Override
		public void update() {
			System.out.println("观察者 A 检测到了变化");
		}
	}

	static class ObserverB implements Observer{

		@Override
		public void update() {

			System.out.println("观察者 B 检测到了变化");
		}
	}

	static class ConcreteObserve extends ObserverManager{

		@Override
		public void change() {

			System.out.println("我变化了");
			notifyAllObserver();
		}
	}
}
